from django.shortcuts import render
from django.views import View
from django import http
from django.conf import settings
import os,json

from meid_duo.utils.views import LoginRequiredView
from meid_duo.utils.response_code import RETCODE
from orders.models import OrderInfo,OrderGoods
from alipay import AliPay
from .models import Payment
from goods.models import SKU

# Create your views here.

class PaymentView(LoginRequiredView):
    """支付宝链接"""
    def get(self,request,order_id):
        try:  # 检验
            order = OrderInfo.objects.get(order_id=order_id,user=request.user,status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except OrderInfo.DoesNotExist:
            return http.HttpResponseForbidden("订单有误")

        alipay = AliPay( # 创建alipay对象
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),'keys/app_private_key.pem'),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),'keys/alipay_public_key.pem'),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )
        # 调用它的方法api_alipay_trade_page_pay得到支付链接后面的查询参数部分
        order_string = alipay.api_alipay_trade_page_pay(
            subject='美多商城%s' % order_id,
            out_trade_no=order_id,
            total_amount=str(order.total_amount),  # 类型转换
            return_url=settings.ALIPAY_RETURN_URL
        )
        # 路由拼接
        alipay_url = settings.ALIPAY_URL + "?" + order_string

        return http.JsonResponse({"code":RETCODE.OK,"errmsg":"OK","alipay_url":alipay_url})


class PaymentStatusView(LoginRequiredView):
    """校验支付结果,及修改订单状态"""
    def get(self,request):
        # 获取数据对象
        query_dict = request.GET
        # 数据转换为字典，才有pop方法
        data = query_dict.dict()
        # pop()方法获取数据，删除指定键及值，有返回值，且返回值为删除的值
        sign = data.pop('sign')

        # 测试账号：vuqsuy3884@sandbox.com
        alipay = AliPay(  # 创建alipay对象
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/app_private_key.pem'),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),'keys/alipay_public_key.pem'),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )
        # 检验支付结果，alipay对象的verify()方法
        success = alipay.verify(data,sign)
        if success:  # 获取数据
            order_id = data.get('out_trade_no')
            trade_id = data.get('trade_no')
            try:  # 数据验证
                Payment.objects.get(order_id=order_id,trade_id=trade_id)
            except Payment.DoesNotExist:  # 创建模型保存
                Payment.objects.create(
                    order_id=order_id,
                    trade_id=trade_id
                )
                # 更改订单状态，待支付 ==> 待评价
                OrderInfo.objects.filter(user=request.user,order_id=order_id,status=OrderInfo.ORDER_STATUS_ENUM["UNPAID"]).update\
                    (status=OrderInfo.ORDER_STATUS_ENUM["UNCOMMENT"])
                return render(request,'pay_success.html',{'trade_id':trade_id})
        else:
            return http.HttpResponseForbidden('非法请求')


